<?php

namespace MoChat\App\Statistic\Action\WorkOutside;

use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Arr;
use MoChat\App\Client\Constants\ClientFollowRecordTypeCode;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 跟进统计列表
 * @Controller
 */
class Index extends AbstractAction
{
    /**
     * 外勤列表
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workOutside/index", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $list = Db::table('client as client')
            ->when(isset($data['is_follow']) && is_numeric($data['is_follow']), function (Builder $query) use ($data) {
                if ($data['is_follow'] == 0) {
                    $query->whereNotExists(function (Builder $query) use ($data) {
                        $startTime = date('Y-m-d H:i:s', strtotime('-1 month'));
                        $endTime = date('Y-m-d H:i:s');
                        $query->from('client_follow_record as record')
                            ->whereColumn('record.client_id', 'client.id')
                            ->where('record.created_at', '>=', $startTime)
                            ->where('record.created_at', '<', $endTime);
                    });
                }
                if ($data['is_follow'] == 1) {
                    $query->whereExists(function (Builder $query) use ($data) {
                        $startTime = date('Y-m-d H:i:s', strtotime('-1 month'));
                        $endTime = date('Y-m-d H:i:s');
                        $query->from('client_follow_record as record')
                            ->whereColumn('record.client_id', 'client.id')
                            ->where('record.created_at', '>=', $startTime)
                            ->where('record.created_at', '<', $endTime);
                    });
                }
            })
            ->when(isset($data['user_type']) && is_numeric($data['user_type']), function (Builder $query) use ($data) {
                $query->where('client.b2b_user_type', $data['user_type']);
            })
            ->where('client.is_failure',0)
            ->select([
                'client.id',
                'client.unique_id',
                'client.enterprise_name',
                'client.b2b_user_type',
                'client.review',//是否审核通过
                'client.work_employee_id'
            ])->groupBy(['client.id'])->paginate((int)($data['perPage'] ?? 15));
        $list || $list = collect([]);
        $list = $list->toArray();
        if (!empty($list['data'])) {
            $startTime = date('Y-m-d H:i:s', strtotime('-1 month'));
            $endTime = date('Y-m-d H:i:s');
            $clientIds = array_column($list['data'], 'id');
            $workEmployeeIds = array_column($list['data'], 'work_employee_id');
            //打卡
            $clockRecord = Db::table('clock_record as record')
                ->whereIn('client_id', $clientIds)
                ->where('record.created_at', '>=', $startTime)
                ->where('record.created_at', '<', $endTime)
                ->select([
                    Db::raw('COUNT(*) as count'),
                    'client_id',
                ])->groupBy([
                    'client_id'
                ])->get();
            $clockRecord || $clockRecord = collect([]);
            $clockRecord = $clockRecord->toArray();

            $clockRecord = empty($clockRecord) ? [] : array_column($clockRecord, null, 'client_id');
            $clientFollowRecord = Db::table('client_follow_record as record')
                ->whereIn('client_id', $clientIds)
                ->where('record.created_at', '>=', $startTime)
                ->where('record.created_at', '<', $endTime)
                ->select([
                    Db::raw('COUNT(*) as count'),
                    'client_id',
                ])->groupBy([
                    'client_id'
                ])->get();
            $clientFollowRecord || $clientFollowRecord = collect([]);
            $clientFollowRecord = $clientFollowRecord->toArray();
            $clientFollowRecord = empty($clientFollowRecord) ? [] : array_column($clientFollowRecord, null, 'client_id');
            $workEmployees = Db::table('work_employee')
                ->whereIn('id', $workEmployeeIds)
                ->pluck('name', 'id');
            $workEmployees || $workEmployees = collect([]);
            $workEmployees = $workEmployees->toArray();

            $uniqueIds = array_column($list['data'], 'unique_id');
            $users= Db::connection('b2b')->table('user')
                ->whereIn('unique_id',$uniqueIds)
                ->pluck('review','unique_id');
            $users || $users = collect([]);
            $users = $users->toArray();

            $clockTotal = Db::table('clock_record')
                ->count();
            $list['clockTotalCount'] = $clockTotal;

            $clientTotal= Db::table('client_follow_record as record')
                ->where('record.created_at', '>=', $startTime)
                ->where('record.created_at', '<', $endTime)
                ->select([
                    Db::raw('COUNT(DISTINCT mc_record.client_id) as count'),
                ])->first();
            $clientTotal = $clientTotal->count ?? 0;
            $list['totalClient']=Db::table('client')->where('is_failure',0)->count();
            $list['clientFollowTotalCount'] = $list['totalClient']-$clientTotal;
            foreach ($list['data'] as &$datum) {
                $key = $datum->id;
                $datum->clockCount = $clockRecord[$key]->count ?? 0;
//                $list['clockTotalCount'] += $datum->clockCount;
                $datum->clientFollowCount = $clientFollowRecord[$key]->count ?? 0;
                $datum->workEmployees = $workEmployees[$datum->work_employee_id] ?? "";
                $datum->review = (int)($users[$datum->unique_id] ?? 0);
//                $list['clientFollowTotalCount'] += $datum->clientFollowCount;
                switch ($datum->b2b_user_type) {
                    case 1:
                        $datum->userTypeString = "药店";
                        break;
                    case 2:
                        $datum->userTypeString = "诊所";
                        break;
                    case 3:
                        $datum->userTypeString = "连锁";
                        break;
                    case 4:
                        $datum->userTypeString = "商业公司";
                        break;
                    default:
                        $datum->userTypeString = "未知";
                }
                switch ($datum->review) {
                    case 0:
                        $datum->reviewStrinng = "未通过";
                        break;
                    case 1:
                        $datum->reviewStrinng = "已通过";
                        break;
                    default:
                        $datum->reviewStrinng = "未知";
                }
            }
            unset($datum);
        }
        return $list;
    }
}
